package algorithms.tree;


import mybatis.yuandengta.yuandengta.pojo.Orders;
import mybatis.yuandengta.yuandengta.pojo.User;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.ParserContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.lang.reflect.Method;
import java.util.Optional;

public class Parser1 {

    public void exampleMethod(String param1, int param2) {
        // 示例方法
    }

    public static void main(String[] args) throws NoSuchMethodException {
        // 获取方法参数命名
        DefaultParameterNameDiscoverer discoverer = new DefaultParameterNameDiscoverer();
        User user =new User();
        Orders orders = new Orders();
        orders.setId(1);


        Method method = Parser1.class.getMethod("exampleMethod", String.class, int.class);
        String[] parameterNames = discoverer.getParameterNames(method);
        EvaluationContext context = new StandardEvaluationContext();
        for (int i = 0; i < parameterNames.length; i++) {
            context.setVariable("i" + i, parameterNames[i]);
        }
        Expression expression = parser.parseExpression("#{#i0}", ParserContext.TEMPLATE_EXPRESSION);
        System.err.println(expression.getValue(context,String.class));
        for (String parameterName : parameterNames) {
            System.out.println(parameterName);
        }
    }

    private static final ExpressionParser parser = new SpelExpressionParser();
    private static final DefaultParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer();

    public static String parseSpEl(Method method, Object[] args, String spEl) {
        String[] params = Optional.ofNullable(parameterNameDiscoverer.getParameterNames(method)).orElse(new String[]{});//解析参数名
        EvaluationContext context = new StandardEvaluationContext();
        for (int i = 0; i < params.length; i++) {
            context.setVariable(params[i], args[i]);
        }
        Expression expression = parser.parseExpression(spEl);
        return expression.getValue(context, String.class);
    }


}
